/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.branchstores;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.MaterialType;
import com.qinyeit.serviceapp.entity.enums.State;
import com.qinyeit.serviceapp.service.branchstores.BranchWarehouseService;
import com.qinyeit.serviceapp.service.branchstores.MaterialCostDetailService;
import com.qinyeit.serviceapp.service.branchstores.MaterialCostService;
import com.qinyeit.serviceapp.service.dishes.DishesStoreService;
import com.qinyeit.serviceapp.service.materials.MaterialCategoryService;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.SearchFilterHelper;
import com.qinyetech.springstage.core.entity.search.SearchOperator;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * ClassName: MaterialCostsController <br/>
 * Function: materialCost [成本卡] <br/>
 * date: 2018-12-01 14:09:56 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/branchstores/materialCosts")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_materialCost:read",name ="成本卡",deleteAble = false)
public class MaterialCostsController extends BaseManagementController{

	@Autowired
	private MaterialCostService materialCostService;
	@Autowired
	private DishesStoreService dishesStoreService;
	@Autowired
	private BranchWarehouseService branchWarehouseService;
	@Autowired
	private MaterialCostDetailService materialCostDetailService;
	@Autowired
	private MaterialCategoryService materialCategoryService;
	@Autowired
	private MaterialService materialService;
	private final String [] keys = {"id","storeId","dishesId","specId","warehouseId","processQty","materialCost","otherCost","cost","remark"};
    private final String [] keys1 = {
            "material.id:id", "material.unit:unit", "material.no:code","material.name:name",
            "material.goodsSpec:goodsSpec","material.consumeUnit:consumeUnit",
            "material.orderPriceBom:orderPriceBom","material.purchaseNewPrice:purchaseNewPrice",
            "expend:count","principal:isMain","remark:memo","total:price",
            "newTotal:newPrice","material.consumeRates:consumeRates","material.code:codes"};

    @RequiresPermissions("management_materialCost:show")
    @PermissionInfo(code = "management_materialCost:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        Page<Map<String,Object>> list = materialCostService.findAllForDishes(searchable, CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        QyMap map = QyMap.map("materialCostPage",list);
        //菜品库
        searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("state_eq", State.NORMAL);
        List<DishesStore> dishesStoreList = dishesStoreService.findWithSort(searchable);
        map.setv("stores",JSONUtils.include(dishesStoreList,"id","name"));
        return ok("查询成功",map);
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long id, String specId,Long storeId){
        QyMap map=QyMap.NEW();
        long sId=0l;
        if(specId!=null && !specId.equals("null")){
            sId=Long.valueOf(specId);
        }
        Object obj=materialCostService.findDishOne(sId,id,CurrentAccountUtils.getAuthenticatedMerchantGroupID(),storeId);
        map.setv("dishes",obj);
        Searchable searchable=SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("storeId_eq",storeId);
        searchable.addSearchParam("dishesId_eq",id);
        if(specId!=null && !specId.equals("null")){
            searchable.addSearchParam("specId_eq",specId);
        }
        MaterialCost materialCost=materialCostService.findOne(searchable);
        if(materialCost!=null){
            searchable=SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("cost.id_eq",materialCost.getId());
            List<MaterialCostDetail> materialCostDetails=materialCostDetailService.findWithSort(searchable);
            if(CollectionUtils.isNotEmpty(materialCostDetails)){
                materialCostDetails.forEach(x->{
                    x.setMaterial(materialService.findById(x.getMaterialId()));
                });
            }

            //TODO 在编辑成本卡的时候将库存成本价格查询出来
//            mapList = stockService.listAddStock(mapList, materialCost.getWarehouse().getId());

            map.setv("materialCostDetail", JSONUtils.include(materialCostDetails,keys1));

            map.setv("materialCost",JSONUtils.include(materialCost, keys));
        }else{
            map.setv("materialCost",JSONUtils.include(new MaterialCost(), keys));
        }
        initFormDate(map);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_materialCost:create")
    @PermissionInfo(code = "management_materialCost:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@RequestBody JSONObject materialCost, BindingResult bindingResult){
//        if(materialCostService.exists(buildExists(null, "no", materialCost.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        materialCostService.saveData(materialCost,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute MaterialCost materialCost){
        return ok("查询成功", JSONUtils.include(materialCost, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute MaterialCost materialCost){
        QyMap map=QyMap.NEW();
        map.setv("materialCost",JSONUtils.include(materialCost, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_materialCost:update")
    @PermissionInfo(code = "management_materialCost:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid MaterialCost materialCost,BindingResult bindingResult){
//        if(materialCostService.exists(buildExists(null, "no", materialCost.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        materialCostService.update(materialCost);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_materialCost:destory")
    @PermissionInfo(code = "management_materialCost:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/destory")
    public ResponseResult<String> destory(Long id,Long specId,Long storeId){
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("dishesId_eq", id);
        searchable.addSearchParam("specId_eq",specId);
        searchable.addSearchParam("storeId_eq",storeId);
        MaterialCost materialCost = materialCostService.findOne(searchable);
        if (materialCost != null) {
            materialCost.setUpdateTimestamp(DateUtils.current());
            materialCostService.update(materialCost);
            materialCostService.deleteDetails(materialCost.getId());
            materialCostService.delete(materialCost.getId());
        }
        return ok("删除成功", null);
    }

    /**
     * 获取物料
     */
    @GetMapping("/getMaterials")
    public Object getMaterials(String code, Long categoryIds, Searchable searchable,Long storeId){
        if(storeId==null){
            return fail("菜品库为空");
        }
        if(StringUtils.isNotBlank(code)){
            searchable.addSearchFilter(SearchFilterHelper.or(
                    SearchFilterHelper.newCondition("no_like", code),
                    SearchFilterHelper.newCondition("name_like", code),
                    SearchFilterHelper.newCondition("code_like", ","+code)

            ));
        }

        MaterialCategory category = materialCategoryService.findById(categoryIds);
        if(category!=null){
            searchable.addSearchFilter(SearchFilterHelper.or(
                    SearchFilterHelper.newCondition("category.parentIds_like", category.getParentIds()+category.getId()+"/"),
                    SearchFilterHelper.newCondition("category.id_eq", category.getId())
            ));
        }
        //菜品库下的 或者 共享的
        searchable.addSearchFilter(SearchFilterHelper.or(
                SearchFilterHelper.newCondition("storeId", SearchOperator.eq,storeId),
                SearchFilterHelper.newCondition("storeId",SearchOperator.isNull,null)
        ));

        QyMap map=QyMap.NEW();
        SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<Material> materials= materialService.findAll(searchable);
        if(CollectionUtils.isNotEmpty(materials.getContent())){
            for (Material material : materials.getContent()) {
                if(com.qinyetech.springstage.core.lang.StringUtils.isNotBlank(material.getCode())){
                    //取一个编码
                    if(material.getCode().indexOf(","+code+",")!=-1){
                        material.setGoodcode(code);
                    }else {
                        material.setGoodcode(material.getCode().substring(1,material.getCode().indexOf(",",2)));
                    }
                    //将编码逗号分隔为数组
                    material.setGoodcodes(org.apache.commons.lang3.StringUtils.split(material.getCode(),","));
                }else {
                    material.setGoodcode("");
                    material.setGoodcodes(null);
                }
            }
        }

        map.setv("materials", JSONUtils.include(materials,
                "id","no","name","goodsSpec","consumeUnit","category.name:categoryName",
                "orderPriceBom","purchaseNewPrice","unit", "consumeRates", "state","goodcode","goodcodes"));

        List<MaterialCategory> list=materialCategoryService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),storeId);
        MaterialCategory materialCategory=new MaterialCategory();
        materialCategory.setId(0L);
        materialCategory.setName("所有类别");
        materialCategory.setNo("0");
        list.add(0,materialCategory);
        map.setv("treeData",list);
        return ok("初始化成功", map);
    }


    /**
     * 获取物料
     */
    @GetMapping("/getMaterialsByName")
    public Object getMaterialsByName(String code,Long storeId){
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        if(StringUtils.isNotBlank(code)){
            searchable.addSearchFilter(SearchFilterHelper.or(
                    SearchFilterHelper.newCondition("no_like", code),
                    SearchFilterHelper.newCondition("name_like", code)
            ));
        }
        searchable.addSearchFilter(SearchFilterHelper.or(
                SearchFilterHelper.newCondition("storeId",SearchOperator.eq,storeId),
                SearchFilterHelper.newCondition("storeId",SearchOperator.isNull,null)
        ));
       /* searchable.addSearchFilter(SearchFilterHelper.or(
                SearchFilterHelper.newCondition("materialType",SearchOperator.eq, MaterialType.MATERIAL),
                SearchFilterHelper.newCondition("materialType",SearchOperator.eq, MaterialType.HALF_PRODUCT)

        ));*/
        searchable.addSearchFilter("materialType", SearchOperator.ne, MaterialType.PRODUCT);
        QyMap map=QyMap.NEW();
        searchable.setPage(0,15);
        Page<Material> materialPage= materialService.findAll(searchable);
        List<Material> materials = materialPage.getContent();
        List<QyMap> materialList = Lists.newArrayList();
        if(CollectionUtils.isNotEmpty(materials)){
            QyMap item = null;
            for (Material material : materials) {
                item = QyMap.NEW();
                if(StringUtils.isNotBlank(material.getCode())){
                    //取一个编码
                    if(material.getCode().indexOf(","+code+",")!=-1){
                        item.setv("goodcode",code);
                    }else {
                        item.setv("goodcode",material.getCode().substring(1,material.getCode().indexOf(",",2)));
                    }
                    //将编码逗号分隔为数组
                    item.setv("goodcodes",StringUtils.split(material.getCode(),","));
                }else {
                    item.setv("goodcode","");
                    item.setv("goodcodes",null);
                }
                item.setv("id",material.getId())
                        .setv("no",material.getNo())
                        .setv("name",material.getName())
                        .setv("goodsSpec",material.getGoodsSpec())
                        .setv("consumeUnit",material.getConsumeUnit())
                        .setv("orderPriceBom",material.getOrderPriceBom())
                        .setv("purchaseNewPrice",material.getPurchaseNewPrice())
                        .setv("unit",material.getUnit())
                        .setv("consumeRates",material.getConsumeRates())
                        .setv("state",material.getState())
                        .setv("code",material.getCode());
                materialList.add(item);
            }
        }
//        map.setv("materials", JSONUtils.include(materials,
//                "id","no","name","goodsSpec","consumeUnit",
//                "orderPriceBom","purchaseNewPrice","unit", "consumeRates", "state","code"));
        map.setv("materials",materialList);
        return ok("初始化成功", map);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            MaterialCost materialCost = materialCostService.findById(Long.valueOf(id));
            model.addAttribute(materialCost);
        }
    }


    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //出库仓库
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        List<BranchWarehouse> warehouseList = branchWarehouseService.findWithSort(searchable);
        qyMap.setv("warehouseList",JSONUtils.include(warehouseList,"id","no","name"));

    }

}